package com.b.service.impl;

import com.b.repository.ProductRepository;
import com.b.repository.SeckillActivityRepository;
import jakarta.annotation.Resource;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import com.b.dao.SeckillActivityMapper;
import com.b.domain.SeckillActivity;
import com.b.service.SeckillActivityService;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Service
public class SeckillActivityServiceImpl implements SeckillActivityService{

    @Resource
    private SeckillActivityMapper seckillActivityMapper;
    @Resource
    private SeckillActivityRepository seckillActivityRepository;
    @Resource
    private ProductRepository productRepository;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Override
    @Transactional
    public Boolean deleteByPrimaryKey(Integer id) {
        try {
            seckillActivityMapper.deleteByPrimaryKey(id);
            seckillActivityRepository.deleteById(id);
            return true;
        } catch (Exception e) {
            return false;
        }
    }


    @Override
    @Transactional
    public Boolean insertSelective(SeckillActivity record) {
        try {
            record.setCreateTime(new Date());
            seckillActivityMapper.insertSelective(record);
            productRepository.findById(record.getProductId()).ifPresent(record::setProduct);
            seckillActivityRepository.save(record);
            //把库存存到redis，并设置过期时间为开始时间和结束时间之间的时段
            long expireTime = (record.getEndTime().getTime() - record.getStartTime().getTime()) / 1000; // 转换为秒
            stringRedisTemplate.opsForValue().set("seckill:" + record.getId() + ":stock:" + record.getProductId(),
                    record.getTotalStock().toString(),
                    expireTime,
                    TimeUnit.SECONDS);
            return true;

        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("插入数据失败");
        }
    }


    @Override
    @Transactional
    public Boolean updateByPrimaryKeySelective(SeckillActivity record) {
        try {
            record.setCreateTime(new Date());
            seckillActivityMapper.updateByPrimaryKeySelective(record);
            productRepository.findById(record.getProductId()).ifPresent(record::setProduct);
            seckillActivityRepository.save(record);
            //把库存存到redis，并设置过期时间为开始时间和结束时间之间的时段
            long expireTime = (record.getEndTime().getTime() - record.getStartTime().getTime()) / 1000; // 转换为秒
            stringRedisTemplate.opsForValue().set("seckill:" + record.getId() + ":stock:" + record.getProductId(), 
                                                  record.getTotalStock().toString(), 
                                                  expireTime, 
                                                  TimeUnit.SECONDS);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("更新数据失败");
        }
    }


    @Override
    public Page<SeckillActivity> list(String name, PageRequest pageRequest) {
        Page<SeckillActivity> seckillActivities;

        if (name == null || name.trim().isEmpty()) {
            seckillActivities = seckillActivityRepository.findAll(pageRequest);
        } else {
            // 过滤掉特殊字符
            name = name.replace("*", "").replace("\"", "");
            seckillActivities = seckillActivityRepository.findByNameContainingIgnoreCase(name, pageRequest);
        }

        seckillActivities.getContent().forEach(seckillActivity -> {
            if (seckillActivity.getProductId() != null) {
                productRepository.findById(seckillActivity.getProductId()).ifPresent(seckillActivity::setProduct);
            }
        });

        return seckillActivities;
    }

    @Override
    @Transactional
    public Boolean updateStatus(Integer id, Integer status) {
        try {
            SeckillActivity seckillActivity = seckillActivityRepository.findById(id).orElse(null);
            if (seckillActivity != null) {
                seckillActivity.setStatus(status);
                seckillActivityRepository.save(seckillActivity);
                return true;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }

        return false;
    }
    @Override
    public int insert(SeckillActivity record) {
        return seckillActivityMapper.insert(record);
    }

    @Override
    public int updateByPrimaryKey(SeckillActivity record) {
        return seckillActivityMapper.updateByPrimaryKey(record);
    }
    @Override
    public SeckillActivity selectByPrimaryKey(Integer id) {
        return seckillActivityMapper.selectByPrimaryKey(id);
    }
    @Override
    public List<SeckillActivity> getAll() {
        return seckillActivityMapper.getAll();
    }

}
